package utils

import (
	"encoding/base32"
	"fmt"
	"strconv"
	"time"
)

const encodeCustom = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"
const CustomPadding rune = '0'

var CustomEncoding *base32.Encoding

func init() {
	CustomEncoding = base32.NewEncoding(encodeCustom)
	CustomEncoding = CustomEncoding.WithPadding(CustomPadding)
}
func Reverse(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}
func EncodeString(in string) string {
	return CustomEncoding.EncodeToString([]byte(in))
}

// 解码成字符串
func DecodeString(in string) string {
	if out, err := CustomEncoding.DecodeString(in); err != nil {
		fmt.Printf("decodebase32_%v\n", err)
		return ""
	} else {
		return Reverse(string(out))
	}
}

// 解码时间戳
func DecodeTimeStampString(in string) int64 {
	if out, err := CustomEncoding.DecodeString(in); err != nil {
		return 0
	} else {
		if ts, frr := strconv.Atoi(Reverse(string(out))); frr != nil {
			return 0
		} else {
			return int64(ts)
		}
	}
}

//验证时间戳
func CheckTimeStampString(in string) bool {
	ts := DecodeTimeStampString(in)
	nowts := time.Now().Unix()
	fmt.Println(ts, " ", nowts)
	if nowts < ts {
		return false
	}
	if nowts-ts > 2 {
		return false
	}
	return true
}

func CheckTimeStamp(ts int64) bool {
	nowts := time.Now().Unix()
	if nowts > ts {
		return nowts-ts < 600
	}
	if nowts < ts {
		return ts-nowts < 600
	}
	return true
}
